package com.panda.qqclient.services;

import com.panda.qqcommon.Message;
import com.panda.qqcommon.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class ClientConnectServiceThread extends Thread{


    private Socket socket;

    public Socket getSocket() {
        return socket;
    }

    public ClientConnectServiceThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run(){
        //因为线程需要持续在后台通讯，使用循环
        while(true){
            System.out.println("客户端等待从服务端发送的信号,socket number is:"+socket.getPort());
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                //如果没有收到消息，就会一直阻塞
                Message message=(Message) objectInputStream.readObject();
                if(message.getMessageType().equals(MessageType.MESSAGE_RETURN_ONLINE_LIST)){
                    //如果客户端收到消息，服务端给我们发送的message是一个用户列表
                    String[] onlineUsers=message.getContent().split(" ");
                    System.out.println("目前的用户列表有：");
                    for (String onlineUser : onlineUsers) {
                        System.out.println(onlineUser);
                    }
                break;
                }else if(message.getMessageType().equals(MessageType.MESSAGE_COMMON_MESSAGE)){
                    //将服务器的消息显示到控制台
                    System.out.println(message.getSender()+"给你说"+message.getContent());


                }else if(message.getMessageType().equals(MessageType.MESSAGE_TO_ALL)){
                    System.out.println("\n群发消息（来自"+message.getSender()+"):"+message.getContent());

                }


                else{
                    //暂时不处理
                }




            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

        }

    }
}
